#include "request.h"

using namespace easyWebServer;


Request::Request(int fd)
    : m_fd(fd)
{
    m_conn.setfd(fd);
}

Request::~Request()
{
    m_fd = -1;
}

void Request::recv()
{
    string context = m_conn.recvData();
    bool ret = parse(context);
    if(ret == false)
    {
        return;
    }
}

string Request::operator [] (const string & key)
{
    auto it = m_context.find(key);
    if(it == m_context.end())
    {
        return "";
    }
    return it->second;
}

bool Request::parse(const string & context)
{
    int readed = 0;
    addElem("method", context, readed, " ");
    addElem("url", context, readed, " ");
    addElem("httpVersion", context, readed, "\r\n");
    int pos = context.find("\r\n\r\n", readed);
    while(readed != pos + 2 && pos != -1)
    {
        addElem(findKey(context, readed, ": "), context, readed, "\r\n");
    }    
    return true;
}

void Request::insertPair(const string & key, const string & value)
{
    m_context[key] = value;
}

void Request::addElem(const string & key, const string & context, int & start, const string & patten)
{
    int pos = context.find(patten, start);
    m_context[key] = context.substr(start, pos - start);
    start = pos + patten.size();
}

string Request::findKey(const string & context, int & start, const string & patten)
{
    int pos = context.find(patten, start);
    string out = context.substr(start, pos - start);
    start = pos + patten.size();
    return out;
}

void Request::showAllKeyValue()
{
    for(auto it = m_context.begin(); it != m_context.end(); it++)
    {
        cout << it->first << ": " << it->second << endl;
    }
}

